﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.IO;
using cnFederal.FaCode;

namespace cnFederal.Admin
{
    public partial class EditSelectedNation : System.Web.UI.Page
    {
        Nation _nation;
        List<CnfiUser> _cnfiUsers;
        CultureInfo _ci;
        string _imageUrl;
        public EditSelectedNation()
        {
            _ci = new CultureInfo("nb-NO");
            CnfiUsers.Load();
            CnfImages.Load();
            Nations.Load("Farsi");
            _cnfiUsers = CnfiUsers.GetAllUsers();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            int id = -1;
         
            string query = Request.QueryString["Id"];
            if (string.IsNullOrWhiteSpace(query))
                txtRegDate.Text = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day;
            if (!IsPostBack)
                InitializeListbox();
            if (!string.IsNullOrWhiteSpace(query))
            {

                try
                {
                    id = int.Parse(query);
                }
                catch (Exception ex) { }
                if (id != -1)
                    Load(id);

            }
            if (Session["ImageUrl"] != null)
                this._imageUrl = Session["ImageUrl"].ToString();
            
            ValidForm();
            MainTable.Visible = UserIdentity.Autenticated;
        }
        private bool _valid;
        private void ValidForm()
        {
            bool valid = true;
            if (string.IsNullOrWhiteSpace(txtTitle.Text)
                || string.IsNullOrWhiteSpace(txtHeader.Text)
                || string.IsNullOrWhiteSpace(txtContent.Text))
            {
                valid = false;
                Label_Error.Text = "Title, header or content can not be null";
            }
            else
                Label_Error.Text = "";
            _valid = valid;
        }

        public string ImageUrl
        {
            get { return _imageUrl; }
            set { _imageUrl = value; }
        }

        public void Load(int id)
        {
            _nation = Nations.GetFaPostById(id);
            if (!IsPostBack && _nation != null)
            {
                DropDownListAuthor.SelectedValue = Convert.ToString(_nation.AuthorId);
                DropDownListNations.SelectedValue = Convert.ToString(_nation.NationId);
                DropDownListCategory.SelectedValue = _nation.Category;
                DropDownListType.SelectedValue = _nation.Language;
                txtRegDate.Text = _nation.DateRegistered.Year + "-" + _nation.DateRegistered.Month + "-" + _nation.DateRegistered.Day;
                txtTitle.Text = _nation.Title;
                
                txtHeader.Text = _nation.Header;
                txtContent.Text = _nation.MainContent;
                if (_nation.Display == true)
                    RadioButtonEnable.Checked = true;
                else
                    RadioButtonDisable.Checked = true;
                imageSelected.ImageUrl = _nation.ImageUrl;
            }
        }
        protected void txtRegDate_TextChanged(object sender, EventArgs e)
        {



        }

        protected void txtDateStartPublish_TextChanged(object sender, EventArgs e)
        {
            //_fapost.DateStartPublish = DateTime.Parse(txtDateStartPublish.Text);


        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int itemId = 0;
            if (_valid)
            {
                if (_nation == null)
                   itemId =  CreateNew();
                else
                    Update();
                this.Label_Error.Text = "";
                string id = Request.QueryString["Id"];
                if (!string.IsNullOrWhiteSpace(id))
                {
                    if (itemId == 0)
                        itemId = Convert.ToInt32(id);
                    if (_image != null)
                    {
                        _image.LinkId = itemId;
                        _image.LinkType = (int)SysObjects.NATION;
                        CnfImages.Save(_image);
                    }
                }
                string query = @"~/Admin/EditSelectedNation.aspx";
                Response.Redirect(query);
            }
            else
                this.Label_Error.Text = "Title, header or content can not be null";
        }


        private void Update()
        {
            if (!string.IsNullOrWhiteSpace(DropDownListAuthor.SelectedValue))
                _nation.AuthorId = Convert.ToInt32(DropDownListAuthor.SelectedValue);
            _nation.Category = DropDownListCategory.SelectedValue;
            _nation.NationId = Convert.ToInt32(DropDownListNations.SelectedValue);
            _nation.Language = DropDownListType.SelectedValue;
            _nation.Header = txtHeader.Text;
            if (!string.IsNullOrWhiteSpace(this.ImageUrl))
                _nation.ImageUrl = this.ImageUrl;
            _nation.MainContent = txtContent.Text;
            _nation.Title = txtTitle.Text;
            if (RadioButtonEnable.Checked)
                _nation.Display = true;
            else
                _nation.Display = false;
            Nations.Save(_nation);
        }

        private int CreateNew()
        {

            _nation = new Nation();
            _nation.AuthorId = Convert.ToInt32(DropDownListAuthor.SelectedValue); ;
            _nation.Category = DropDownListCategory.SelectedValue;
            _nation.NationId = Convert.ToInt32(DropDownListNations.SelectedValue);
            _nation.Language = DropDownListType.SelectedValue;
            _nation.DateRegistered = DateTime.Now;
            _nation.Header = txtHeader.Text;
            _nation.ImageUrl = this.ImageUrl;
            _nation.MainContent = txtContent.Text;
            _nation.Title = txtTitle.Text;
            if (RadioButtonEnable.Checked)
                _nation.Display = true;
            else
                _nation.Display = false;
           return Nations.CreateNew(_nation);


        }

        protected void btnBrows_Click(object sender, EventArgs e)
        {
            UploadImage();
            //Response.Redirect(Request.RawUrl);

        }


        public string RootDomain
        {
            get
            {
                return HttpContext.Current.Request.Url.Authority;
            }
        }
        public string AbsoluteURI
        {
            get
            {
                return HttpContext.Current.Request.Url.AbsoluteUri;
            }
        }
        CnfImage _image;
        private void UploadImage()
        {
            string msg = "";
            if (fileupload1.HasFile)
            {
                try
                {
                    string[] sTypes = { "image/jpg", "image/jpeg", "image/pjpeg", "image/gif", "image/x-png", "image/png" };
                    bool bIsMatch = false;
                    foreach (string sType in sTypes)
                    {
                        if (String.Compare(sType, fileupload1.PostedFile.ContentType, true) == 0)
                            bIsMatch = true;
                    }

                    if (bIsMatch)
                    {
                        if (fileupload1.PostedFile.ContentLength < 1002400)
                        {
                            // string appPath = Request.PhysicalApplicationPath;

                            string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
                            //fileupload1.SaveAs(Server.MapPath(Path.Combine("~/Images/", filename)));
                            _image = CnfImages.GetImageByName(fileupload1.FileName);
                            if (_image == null)
                            {
                                CnfImage img = new CnfImage();
                                img.Image = fileupload1.FileBytes;
                                img.ImageName = fileupload1.FileName;
                                if (_nation != null)
                                    img.LinkId = _nation.Id;
                                img.LinkType = (int)SysObjects.NATION;
                                CnfImages.CreateNew(img);
                                _image = CnfImages.GetLastAddedImage();

                            }
                           // this._imageUrl = "http://cnfi.info/ImgHandler.ashx?id=" + _image.Id;
                            this._imageUrl = "http://" + RootDomain + "/ImgHandler.ashx?id=" + _image.Id;
                            Session["ImageUrl"] = this._imageUrl;
                            this.imageSelected.ImageUrl = this._imageUrl;

                        }
                        else
                            msg = "Upload status: The file has to be less than 1 MB!";
                    }
                    else
                        msg = "Upload status: Only JPEG files are accepted!";
                }
                catch (Exception ex)
                {
                    msg = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }

        }

        //private void UploadImage()
        //{
        //    string msg = "";
        //    if (fileupload1.HasFile)
        //    {
        //        try
        //        {
        //            if (fileupload1.PostedFile.ContentType == "image/jpeg")
        //            {
        //                if (fileupload1.PostedFile.ContentLength < 1002400)
        //                {
        //                    string filename = Path.GetFileName(fileupload1.FileName);
        //                    fileupload1.SaveAs(Server.MapPath("~/Images/") + filename);
        //                    this._imageUrl = "~/Images/" + filename;
        //                    Session["ImageUrl"] = this._imageUrl;
        //                    this.imageSelected.ImageUrl = this._imageUrl;

        //                }
        //                else
        //                    msg = "Upload status: The file has to be less than 1 MB!";
        //            }
        //            else
        //                msg = "Upload status: Only JPEG files are accepted!";
        //        }
        //        catch (Exception ex)
        //        {
        //            msg = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        //        }
        //    }
        //}


        private void InitializeListbox()
        {

            if (_cnfiUsers != null && _cnfiUsers.Count != 0)
            {

                foreach (CnfiUser u in _cnfiUsers)
                {
                    ListItem item = new ListItem(u.Name, u.Id.ToString());
                    DropDownListAuthor.Items.Add(item);
                }
                ListItem nullItem = new ListItem("", "");
                nullItem.Selected = true;
                DropDownListAuthor.Items.Add(nullItem);

            }

        }
        private string _category;
        private int _AuthorId;

        protected void DropDownListAuthor_SelectedIndexChanged(object sender, EventArgs e)
        {
            _AuthorId = Convert.ToInt32(DropDownListAuthor.SelectedValue);
        }

        protected void DropDownListCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            _category = DropDownListCategory.SelectedItem.Text;
        }

        private bool _display;
        protected void RadioButtonEnable_CheckedChanged(object sender, EventArgs e)
        {
            _display = true;
        }

        protected void RadioButtonDisable_CheckedChanged(object sender, EventArgs e)
        {
            _display = false;
        }

        protected void DropDownListNations_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void txtHeader_TextChanged(object sender, EventArgs e)
        {
            ValidForm();
        }

        protected void txtTitle_TextChanged(object sender, EventArgs e)
        {
            ValidForm();
        }

        protected void txtContent_TextChanged(object sender, EventArgs e)
        {
            ValidForm();
        }
       








    }
}